#include "config.h"
#include "isr.h"

#define SYSTICK
//#define EXTI
//#define TIMER

#ifdef SYSTICK
// SysTick interrupt handler - called every 1 ms (configured by SysConfig)
void SysTick_Handler(void)
{
	msTicks++;
}
#endif

#ifdef EXTI
/*
 * Group1 IRQ handler handles GPIOA interrupts among others.
 * SysConfig enabled PA7 (GPIOA pin 7) as falling edge interrupt.
 */
void GROUP1_IRQHandler(void)
{
	/* Check if GPIOA PA7 triggered (enabled interrupt status) */
	if (DL_GPIO_getEnabledInterruptStatus(ENCODER_PORT, ENCODER_EC11_KEY_PIN) & ENCODER_EC11_KEY_PIN)
	{
		/* Clear the interrupt flag for PA7 */
		DL_GPIO_clearInterruptStatus(ENCODER_PORT, ENCODER_EC11_KEY_PIN);
		/* Set a flag for the main loop or other tasks to process */
		encoderEvent = 1;
	}

	/* If other Group1 sources exist, optionally check/clear them here.
	 * DL_Interrupt_getStatusGroup and DL_Interrupt_clearGroup can be used
	 * for group-level handling if needed.
	 */
	
}

#endif

#ifdef TIMER

void TIM0_INST_IRQHandler(void)
{
	/* Check if TIM0 update interrupt is pending */
	if (DL_Timer_getPendingInterrupt(TIM0_INST) & DL_TIMERA_INTERRUPT_LOAD_EVENT)
	{
		/* Clear the interrupt flag */
		DL_Timer_clearInterruptStatus(TIM0_INST, DL_TIMERA_INTERRUPT_LOAD_EVENT);
		
		// 原始按键读取：0 = 按下，1 = 释放
		uint8_t raw = (DL_GPIO_readPins(ENCODER_PORT, ENCODER_EC11_KEY_PIN) & ENCODER_EC11_KEY_PIN) ? 1 : 0;

		// 8-bit 移位寄存器消抖（每1ms采样一次 8ms 为一个窗口）
		static uint8_t key_hist = 0xFF;
		static uint8_t key_stable = 1; // 1 表示稳定，初始状态为稳定释放

		key_hist = (uint8_t)((key_hist << 1) | raw);

		if (key_hist == 0x00 && key_stable != 0) {
			key_stable = 0;
			keyPressEvent = 1; // 稳定按下事件
		} else if (key_hist == 0xFF && key_stable != 1) {
			key_stable = 1;
			// 可设置释放事件（如需）
		}
	}
}

#endif